package edu.dayu.Test;


public class MyHashMap<K,V> {
    private entry<K,V>[] entry;
    private int len = 16;
    private final float factor = 0.75f;


    public MyHashMap(){
        entry = new entry[16];
    }

    public void put(K key,V value){
        if (size()>=(int)(len*factor))
            resize();
        int k = key.hashCode()&(len-1);
        //  判断该节点上是否含有值
        V val = entry[k]==null?null: entry[k].value;
        if (val!=null){
            entry[k] = new entry<K,V>(value,key,entry[k]);
        }else
        entry[k] = new entry<>(value,key,null);
    }

    public V get(K key){
        int k = key.hashCode()&(len-1);
        entry<K,V> entry2 = entry[k]==null?null: entry[k];
        V value = null;
        // 如果存在多个值，就按照 key 来获取。
        while (entry2!=null){
            if (entry2.key.equals(key)) {
                value = entry2.value;
                break;
            }
            entry2 = entry2.next;
        }
        return value;
    }

    public int size(){
        int len = 0;
        for (int i = 0; i < entry.length; i++) {
            entry entry1 = entry[i];
            while (entry1!=null){
                entry1 = entry1.next;
                len++;
            }
        }
        return len;
    }


    private void resize(){
        // 直接扩大一倍
        len = len*2;
        entry<K,V>[] entries = new entry[len];
        for (int i = 0; i < entry.length; i++) {
            while (entry[i]!=null){
                int j = entry[i].key.hashCode()&(len-1);
                entries[j] = new entry<>(entry[i].value,entry[i].key,null);
                entry[i] = entry[i].next;
            }
        }
        entry = entries;
    }

    // 用于存储值的类
    static class entry<K,T>{
        K key;
        T value;
        entry<K,T> next;
        private entry(T value,K key,entry<K,T> next){
            this.value = value;
            this.next = next;
            this.key = key;
        }
    }


    public static void main(String[] args) {
        MyHashMap<Integer, String> myHashMap = new MyHashMap<>();
        myHashMap.put(2,"你好");
        myHashMap.put(18,"你好2");
        myHashMap.put(11,"你好2");
        myHashMap.put(12,"你好2");
        myHashMap.put(13,"你好2");
        myHashMap.put(14,"你好2");
        myHashMap.put(15,"你好2");
        myHashMap.put(16,"你好2");
        myHashMap.put(17,"你好2");
        myHashMap.put(19,"你好2");
        myHashMap.put(10,"你好2");
        myHashMap.put(28,"你好2");
        myHashMap.put(38,"你好2");
        myHashMap.put(48,"你好2");
        System.out.println(myHashMap.get(2));
        System.out.println(myHashMap.get(18));
        System.out.println(myHashMap.size());
    }
}
